package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.usian.common.aliyun.OSSService;
import com.usian.common.dtos.PageResult;
import com.usian.common.enums.AppHttpCodeEnum;
import com.usian.common.exception.LeadException;
import com.usian.common.threadlocal.UserThreadLocalUtils;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.wemedia.entity.WmMaterial;
import com.usian.wemedia.entity.WmNewsMaterial;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.wemedia.service.IWmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author usian
 * @since 2022-07-07
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Autowired
    private OSSService ossService;


    @Override
    public String uploadPic(MultipartFile file) {
        //对file做判断 file不能为空
        if (StringUtils.isEmpty(file)){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"上传文件为空");
        }
        //获取用户的id 图片资源库需要存储用户的id 用户的id放到了线程中
        Integer userId = UserThreadLocalUtils.getUserId();

        //如果file不为空 进行上传文件
        try {
            String url = ossService.upload(file);//返回路径
            WmMaterial wmMaterial = new WmMaterial();
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setUrl(url);
            wmMaterial.setUserId(userId);
            wmMaterial.setIsCollection(false); //初始化数据为false
            wmMaterial.setType(0);
            //添加数据
            save(wmMaterial);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR, "图片上传失败");
        }
    }

    @Override
    public PageResult<WmMaterial> findByPage(WmMaterialDto wmMaterialDto) {
        if (wmMaterialDto==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"参数不正确");
        }
        //获取userId
        Integer userId = UserThreadLocalUtils.getUserId();
        //设置查询条件
        if (userId==null){
            throw new LeadException(AppHttpCodeEnum.PARAM_INVALID,"userId为空");
        }
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询必须是userId的
        lambdaQueryWrapper.eq(WmMaterial::getUserId,userId);
        //是否是收藏的
        Boolean collection=null;
        //如果不为空
        if (wmMaterialDto.getIsCollection()!=null){
            //如果是0的话就是不收藏
            if (wmMaterialDto.getIsCollection().equals("0")){
                collection=false;

            }else {
                //如果是1的话就是收藏
                collection=true;
                lambdaQueryWrapper.eq(WmMaterial::getIsCollection,collection);
            }

        }

        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page page = new Page(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        IPage<WmMaterial> materialIPage= page(page,lambdaQueryWrapper);
        //如果查询的数据为空
        if (materialIPage==null || CollectionUtils.isEmpty(page.getRecords())){
            //返回数据不存在
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return new PageResult<>(wmMaterialDto.getPage(),wmMaterialDto.getSize(),materialIPage.getTotal(),materialIPage.getRecords());
    }

    /**
     * 收藏和取消收藏
     * @param id
     * @param b
     */
    @Override
    public void updateCollect(Integer id, boolean b) {
        //从线程中获取id
        Integer userId = UserThreadLocalUtils.getUserId();
        LambdaUpdateWrapper<WmMaterial> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //构建修改条件
        lambdaUpdateWrapper.eq(WmMaterial::getId,id);
        lambdaUpdateWrapper.eq(WmMaterial::getUserId,userId);
        lambdaUpdateWrapper.set(WmMaterial::getIsCollection,b);
        update(lambdaUpdateWrapper);
    }

    /**
     * 删除图片
     * @param id
     */


    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;
    @Autowired
    private IWmMaterialService wmMaterialService;

    @Override
    public void delPicture(Integer id) {
        if (id==null) {
            throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //获取用户id
        Integer userId = UserThreadLocalUtils.getUserId();
        if (userId==null) {
            throw new LeadException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //删除图片要关联到素材表 看看素材表中是否被引用 如果被引用则不能删除
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        List<WmNewsMaterial> list = wmNewsMaterialService.list(lambdaQueryWrapper);
        //如果长度大于1说明是有数据不能删除
        if (list.size()>0){
            //数据已经被使用无法被删除
            throw new LeadException(AppHttpCodeEnum.DATA_CAN_NOT_DEL,"素材已经被使用不能删除");
        }

        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.eq(WmMaterial::getId,id);
        WmMaterial wmMaterial = wmMaterialService.getOne(lambdaQueryWrapper2);
        int index = wmMaterial.getUrl().lastIndexOf("/")+1;
        String imageName = wmMaterial.getUrl().substring(index);
        ossService.deleteFile(imageName);


        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId);
        boolean b = remove(lambdaQueryWrapper1);
        if (!b){
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }



    }
}
